<?php
/*
 * @Author: Wulala
 * @Date: 2025-03-24 10:40:54
 * @LastEditTime: 2025-04-15 11:34:45
 * @LastEditors: Wulala
 * @Description: 
 * @FilePath: \exchange\app\api\model\Order.php
 * 可以输入预定的版权声明、个性签名、空行等
 */

namespace app\api\model;

use app\common\model\TimeModel;
use app\common\model\MallOrder as MallOrderModel;
use app\common\model\MallOrderGoods as MallOrderGoodsModel;
use app\common\model\MallGoods as MallGoodsModel;
use app\common\model\MallGoodsSku as MallGoodsSkuModel;
use app\common\model\MallOrderCash as MallOrderCashModel;
use think\facade\Db;

class Order
{

   // 下单
   public function placeOrder($params){
      try {
         Db::startTrans(); // 开启事务
         $goods_arr=json_decode($params['goods_arr'],true);
         
         // 新增订单
         unset($params['goods_arr']);
         $params['order_no']=date('YmdHis'.rand(100000,999999));//生成订单号
         $add_order=(new MallOrderModel())->create($params);
        
         // 新增订单商品
         foreach($goods_arr as $k => $v){
            $goodsData=MallGoodsModel::field('id,title')->where('goods_uuid',$v['goods_uuid'])->find();
            if(empty($goodsData)){
               return result_error('未查询到商品信息');
            }
           
            $goodsSkuData=MallGoodsSkuModel::field('id')->where('goods_sku_uuid',$v['goods_sku_uuid'])->find();
            if(empty($goodsSkuData)){
               return result_error('未查询到商品规格信息');
            }
            $goods[$k]['order_id']=$add_order->id;
            $goods[$k]['goods_name']=$goodsData['title'];
            $goods[$k]['goods_uuid']=$v['goods_uuid'];
            $goods[$k]['goods_id']=$goodsData['id'];
            $goods[$k]['goods_sku_uuid']=$v['goods_sku_uuid'];
            $goods[$k]['goods_sku_id']=$goodsSkuData['id'];
            $goods[$k]['num']=$v['num'];
         }

         $res=(new MallOrderGoodsModel)->saveAll($goods);

         Db::commit(); // 提交事务
         return result_success('', $res??[]);
      } catch (\Exception $e) {
         Db::rollback(); // 发生异常时回滚事务
         return result_error($e->getMessage());
      }
   }

   // usdt/paypal下单
   public function placeCash($params){
      try {
         Db::startTrans(); // 开启事务
         $params['order_no']=date('YmdHis').rand(10000000,99999999);
         $res=(new MallOrderCashModel)->save($params);

         Db::commit(); // 提交事务
         return result_success('', $res??[]);
      } catch (\Exception $e) {
         Db::rollback(); // 发生异常时回滚事务
         return result_error($e->getMessage());
      }
   }

}